package com.zyx.crawlerdemo.httpclient.crawler;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author Yaxi.Zhang
 * @since 2021/8/11 16:39
 * desc: Httpclient实例化
 * 	HttpClient实例化方法
 * 		HttpClients.custom()返回值HttpClientBuilder.create()
 * 		HttpClients.createDefault()返回值 HttpClients.custom().build()
 * 		具体可阅读HttpClients类
 */
public class HttpclientInit {
	public static void main(String[] args) throws  ClientProtocolException, IOException, URISyntaxException  {
		HttpClient httpClient1 = new DefaultHttpClient();  
		HttpClient httpClient2 = HttpClients.custom().build(); 
		HttpClient httpClient3 = HttpClientBuilder.create().build();
		CloseableHttpClient httpClient4 = HttpClients.createDefault(); 
		HttpClient httpClient5 = HttpClients.createSystem();
		HttpClient httpClient6 = HttpClients.createMinimal();
		// 创建URI
		URI uri = new URIBuilder("https://searchcustomerexperience.techtarget.com/info/news").build();
		// get方法请求
		HttpGet getMethod = new HttpGet();
		// 设置
		getMethod.setURI(uri);
		// 初始化HTTP响应
		HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
				HttpStatus.SC_OK, "OK");
		// 执行响应
		response = httpClient6.execute(getMethod);
		System.out.println("response:" + response);
		// 响应状态
		String status = response.getStatusLine().toString();
		System.out.println("status:" + status);
		// 获取响应状态码
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println("StatusCode:" + statusCode);
		// 协议的版本号
		ProtocolVersion protocolVersion = response.getProtocolVersion();
		System.out.println("protocolVersion" + protocolVersion);
		// 是否ok
		String phrase = response.getStatusLine().getReasonPhrase();
		System.out.println("phrase:" + phrase);
		System.out.println(response);
		// 状态码200表示响应成功
		if(statusCode == 200){
			// 获取实体内容
			String entity = EntityUtils.toString (response.getEntity(),"gbk");
			// 输出实体内容
			System.out.println(entity);
			// 消耗实体
			EntityUtils.consume(response.getEntity());
		}else {
			// 关闭HttpEntity的流实体
			// 消耗实体
			EntityUtils.consume(response.getEntity());
		}
	}
}

